import type { Menu } from "@/typings";
import { piniaPersistConfig } from "@/config";
import { defineStore } from "pinia";
import { ref } from "vue";

const key: string = "useHistoryStore";

export const useHistoryStore = defineStore(
  key,
  () => {
    // 历史记录
    const history = ref<Menu[]>([]);
    // 添加一条记录
    const addHistory = (item: Menu) => {
      const index = history.value.findIndex((item1) => item1.path === item.path);
      if (index !== -1) {
        history.value.splice(index, 1);
        history.value.unshift(item);
      } else {
        history.value.unshift(item);
      }
    };
    // 清除一条记录
    const clearOneHistory = (item: Menu) => {
      history.value = history.value.filter((item1) => item1.path !== item.path);
    };
    // 清除所有历史记录
    const clearHistory = () => {
      history.value = [];
    };
    return {
      history,
      addHistory,
      clearOneHistory,
      clearHistory
    };
  },
  {
    persist: piniaPersistConfig(key, localStorage)
  }
);
